package com.lagou.edu.utils;

import com.lagou.edu.annotition.MyComponent;

import java.sql.Connection;
import java.sql.SQLException;

@MyComponent("connectionUtils")
public class ConnectionUtils {

	//存储当前线程的连接
	private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

	/**
	 * 从当前线程中获取连接
	 *
	 * @return
	 */
	public Connection getCurrentThreadConn() throws SQLException {
		//判断当前线程中是否已经绑定连接，如果没有绑定，则从数据库连接池中获取一个连接绑定到当前线程
		Connection connection = threadLocal.get();
		if (connection == null) {
			//从数据库连接池拿连接，并绑定到线程
			connection = DruidUtils.getInstance().getConnection();
			//绑定到当前线程
			threadLocal.set(connection);
		}
		return connection;
	}
}
